import { defineComponent, reactive, ref, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElSpace,
  ElButton,
  ElLink,
  ElMessageBox,
  ElMessage,
  ElRow,
  ElCol,
  ElTable,
  ElTableColumn
} from 'element-plus'
import type { TableColumnProps } from '~/components/ProSaasTable/typings'
import type { DemandBatchType, DemandBatchEnum } from './typings'
import SaasTitle from '~/components/SaasTitle'
import AliIcon from '~/components/AliIocn'
import styles from './../index.module.scss'
import ProSaasTable from '~/components/ProSaasTable'
import ImportExcelBatch from './ImportExcelBatch'
import ExportExcel from '~/components/ExportExcel'
import MapLocation from '../components/MapLocationPost'
import useVuexGetters from '~/hooks/useVuexGetters'
import { isURL } from '~/utils/validate'

export default defineComponent({
  props: ['cancel', 'record'],
  setup(props, { expose }) {
    const userState = useVuexGetters('user', ['permission']) // 按钮权限
    const store = useStore()
    const proSaasTableRef = ref()
    const mapLocationRef = ref()
    const state = reactive<DemandBatchEnum>({
      list: [
        { id: '4073ff', num: 150, color: '#4073ff', title: '需求总数' },
        { id: '08AFC6', num: 10, color: '#08AFC6', title: '待查勘数' },
        { id: '40BD5A', num: 50, color: '#40BD5A', title: '匹配数' },
        { id: 'E64554', num: 90, color: '#E64554', title: '不匹配数' },
        { id: 'F59A23', num: 90, color: '#F59A23', title: '抢先建站 ' },
        { id: '23A0A5', num: 100, color: '#23A0A5', title: '50米范围周边有灯杆' },
        { id: 'D9001B', num: 50, color: '#D9001B', title: '50米范围周边无灯杆' }
      ],
      isAction: '4073ff',
      titleStats: -1,
      buildAreas: '',
      discriminateList: [],
      importVisible: false,
      exportVisible: false,
      tableList: [],
      detail: {},
      exportName: ''
    })
    //  数据初始化
    const index = async () => {
      state.discriminateList = []
      const { code, data } = await store.dispatch('base/GetBasebuildbatchTotal', {
        batchNum: props.record.batchNum
      })
      if (code === 200) {
        data.areaList.forEach((item: any) => {
          state.discriminateList.push({
            name: item,
            check: false
          })
        })
        data.totalTitleVOS.forEach((item: any, i: number) => {
          state.list.forEach((value: any, key: number) => {
            if (i < 8 && item.sort + 1 === key) {
              value.num = item.num
              value.title = item.name
              value.key = item.key
            }
          })
        })
      }
    }
    //  列表数据
    const batchList = async (value = true) => {
      const params = {
        batchNum: props.record.batchNum,
        titleStats: state.titleStats,
        buildAreas: state.buildAreas,
        current: 1,
        size: 1000
      }
      const { code, data } = await store.dispatch('base/GetBasebuildbatchBatchList', params)
      if (code === 200) {
        state.tableList = data.records
        if (value) proSaasTableRef.value!.elTableRef.setCurrentRow(data.records[0])
      }
    }
    //  数据切换
    const handDemandClick = (item: any) => {
      state.isAction = item.id
      state.titleStats = item.key

      batchList()
    }
    //  区域切换
    const handDiscriminateClick = (value: any) => {
      value.check = !value.check
      const arr = state.discriminateList?.filter((item) => item.check)
      const array = arr?.map((item) => item.name)
      state.buildAreas = array.join(',')

      batchList()
    }
    //  导出
    const handleChangeExportModal = () => {
      //  工区
      const arr = state.discriminateList?.filter((item) => item.check)
      const array = arr?.map((item) => item.name)
      //  状态
      const array1 = state.list.filter((item) => item.key === state.titleStats)
      //  导出名称
      state.exportName = `${array.join('')}${array1[0].title}`

      state.exportVisible = !state.exportVisible
    }
    // 获取地图信息
    const handleGetBasicInfoById = async (id?: string) => {
      const result = await store.dispatch('base/BasebuildView', {
        id
      })
      state.detail = result?.data
      nextTick(() => {
        setTimeout(() => {
          mapLocationRef.value.onAmbitusLamp()
        }, 500)
      })
    }
    //  设置灯杆显示范围
    const onSetHandleChange = () => {
      index()
    }
    //  加入摘牌库
    const onDelistingLibrary = (row: DemandBatchType) => {
      ElMessageBox.confirm('是否加入摘牌库?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { code, msg } = await store.dispatch('base/GetBasebuildbatchAddBuildDelisting', {
            assetBaseBuildId: row.id
          })

          if (code === 200) {
            batchList(false)
            ElMessage({
              type: 'success',
              message: '操作成功'
            })
          } else {
            ElMessageBox.confirm(msg, '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作'
          })
        })
    }
    //  点击列表
    const handleCurrentChange = (value: any) => {
      handleGetBasicInfoById(value.id)
    }
    //  点击展开
    const onExpandChange = (row: any, expandedRows: any) => {
      if (expandedRows.length > 0) {
        state.detailVOList = row.detailVOList || []
        expandedRows.forEach((item: any) => {
          if (item.id !== row.id) {
            proSaasTableRef.value!.elTableRef.toggleRowExpansion(item)
          } else {
            proSaasTableRef.value!.elTableRef.toggleRowExpansion(item, true)
          }
        })
      }
    }
    const columns: TableColumnProps<DemandBatchType>[] = [
      {
        label: '站点名称',
        prop: 'matchName',
        sortable: true,
        align: 'center',
        minWidth: 160
      },
      {
        label: '规划站号',
        prop: 'matchNum',
        sortable: true,
        align: 'center',
        minWidth: 160,
        render: ({ row }) => (
          <>
            {row.buildStatus === 1 ? <div style="color: red;">{row.matchNum}</div> : row.matchNum}
          </>
        )
      },
      {
        label: '查看全景',
        prop: 'overallViewUrl',
        sortable: true,
        align: 'center',
        minWidth: 120,
        render: ({ row }) => (
          <>
            {isURL(row.overallViewUrl) ? (
              <a href={row.overallViewUrl} target="_blank" style="cursor: pointer; color: blue;">
                查看全景
              </a>
            ) : (
              '-'
            )}
          </>
        )
      },
      {
        label: '查勘状态',
        prop: 'isSurvey',
        sortable: true,
        align: 'center',
        minWidth: 120,
        render: ({ row }) => (
          <>
            {row.isSurvey === 0 && <div>待查勘</div>}
            {row.isSurvey === 1 && <div style="color: blue;">匹配</div>}
            {row.isSurvey === 2 && <div style="color: red;">不匹配</div>}
          </>
        )
      },
      {
        label: '查勘人',
        prop: 'surveyorName',
        sortable: true,
        align: 'center',
        minWidth: 160
      },
      {
        label: '需求类型',
        prop: 'requirementType',
        sortable: true,
        align: 'center',
        minWidth: 120,
        render: ({ row }) => (
          <>{row.requirementType === 2 ? <div style="color: blue;">特批</div> : '常规'}</>
        )
      },
      {
        label: '承建商',
        prop: 'contractor',
        sortable: true,
        hidden: true,
        align: 'center',
        minWidth: 160
      },
      {
        label: '流标原因',
        prop: 'abortiveReson',
        sortable: true,
        hidden: true,
        align: 'center',
        minWidth: 160
      },
      {
        label: '查勘备注',
        prop: 'surveyorMemo',
        sortable: true,
        hidden: true,
        align: 'center',
        minWidth: 160
      },
      {
        label: '操作',
        prop: 'options',
        align: 'center',
        width: 160,
        render: ({ row }) => (
          <ElSpace>
            {row.requirementType === 1 &&
              row.isDelisting === 0 &&
              userState.permission.value.has('station_basebuild_addDelisting') && (
                <ElLink type="primary" onClick={() => onDelistingLibrary(row)}>
                  <AliIcon type="icon-jiaru" />
                  &nbsp;加入摘牌库&nbsp;&nbsp;
                </ElLink>
              )}
            {row.requirementType === 1 && row.isDelisting === 1 && '已入库'}
          </ElSpace>
        )
      }
    ]

    onMounted(() => {
      index()
      batchList()
    })

    expose({ index })
    return () => {
      return (
        <ElCard
          v-slots={{
            header: () => (
              <ElSpace class="info-card-header-space">
                <SaasTitle type="primary">
                  {props.record.batchNum}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  {userState.permission.value.has('station_basebuild_addDelisting') && (
                    <ElButton
                      type="primary"
                      onClick={() => {
                        state.importVisible = true
                      }}
                    >
                      <AliIcon type="icon-daoru" />
                      &nbsp; 导入摘牌结果
                    </ElButton>
                  )}
                </SaasTitle>
                <ElButton text type="primary" onClick={props.cancel}>
                  返回上一级&nbsp;
                  <AliIcon type="icon-fanhuishangyiji" />
                </ElButton>
              </ElSpace>
            )
          }}
        >
          <ul class={styles['demand-batch-data-list']}>
            {state.list.map((item: any) => (
              <li
                class={{
                  [styles['demand-batch-data-item']]: true,
                  [styles[`demand-batch-data-item-${item.id}`]]: state.isAction === item.id
                }}
                style={{ 'border-color': item.color }}
                onClick={() => handDemandClick(item)}
              >
                <p class={styles['demand-batch-data-num']} style={{ color: item.color }}>
                  {item.num}
                </p>
                <p class={styles['demand-batch-data-title']}>{item.title}</p>
              </li>
            ))}
          </ul>
          <ElRow gutter={24}>
            <ElCol {...{ lg: 12, sm: 24 }}>
              <ElRow gutter={24}>
                <ElCol span={5}>
                  <ul class={styles['demand-batch-data-contens-list']}>
                    {state.discriminateList.map((item: any) => (
                      <li
                        class={{
                          [styles['demand-batch-data-contens-item']]: true,
                          [styles['demand-batch-data-contens-item-action']]: item.check
                        }}
                        onClick={() => handDiscriminateClick(item)}
                      >
                        {item.name}
                      </li>
                    ))}
                  </ul>
                </ElCol>
                <ElCol span={19}>
                  <ProSaasTable<DemandBatchType>
                    ref={proSaasTableRef}
                    tableId="DemandBatch"
                    columns={columns}
                    needPagination={false}
                    data={state.tableList}
                    dispatchType="base/GetBasebuildList"
                    searchParams={{
                      batchNum: props.record.batchNum,
                      titleStats: state.titleStats,
                      buildAreas: state.buildAreas,
                      current: 1,
                      size: 1000
                    }}
                    height={600}
                    highlightCurrentRow
                    onCurrent-change={handleCurrentChange}
                    onExpand-change={onExpandChange}
                    headerTitle={
                      <>
                        {userState.permission.value.has('station_basebuild_export') && (
                          <ElButton type="primary" onClick={() => handleChangeExportModal()}>
                            &nbsp; 导出
                          </ElButton>
                        )}
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <span>
                          共计 <span style="color: #4073ff;">{state.tableList?.length}</span> 条数据
                        </span>
                      </>
                    }
                    expand={() => {
                      return (
                        <>
                          <div style="padding: 10px;">
                            <div style="font-size: 16px;">时光机</div>
                            <ElTable data={state.detailVOList} border>
                              <ElTableColumn
                                label="查勘批次"
                                prop="surveyorNum"
                                align="center"
                              ></ElTableColumn>
                              <ElTableColumn
                                label="查勘人"
                                prop="surveyorName"
                                align="center"
                              ></ElTableColumn>
                              <ElTableColumn
                                label="查勘日期"
                                prop="surveyorTime"
                                align="center"
                              ></ElTableColumn>
                              <ElTableColumn
                                label="查看全景"
                                prop="overallViewUrl"
                                align="center"
                                v-slots={{
                                  default: (scope: any) => (
                                    <>
                                      {isURL(scope.row.overallViewUrl) ? (
                                        <a
                                          href={scope.row.overallViewUrl}
                                          target="_blank"
                                          style="cursor: pointer; color: blue;"
                                        >
                                          查看全景
                                        </a>
                                      ) : (
                                        '-'
                                      )}
                                    </>
                                  )
                                }}
                              ></ElTableColumn>
                              <ElTableColumn
                                label="查勘状态"
                                prop="isSurvey"
                                align="center"
                                v-slots={{
                                  default: (scope: any) => (
                                    <>
                                      {scope.row.isSurvey === 0 && <div>待查勘</div>}
                                      {scope.row.isSurvey === 1 && (
                                        <div style="color: blue;">匹配</div>
                                      )}
                                      {scope.row.isSurvey === 2 && (
                                        <div style="color: red;">不匹配</div>
                                      )}
                                    </>
                                  )
                                }}
                              ></ElTableColumn>
                              <ElTableColumn
                                label="查勘备注"
                                prop="surveyorMemo"
                                align="center"
                              ></ElTableColumn>
                            </ElTable>
                          </div>
                        </>
                      )
                    }}
                  ></ProSaasTable>
                </ElCol>
              </ElRow>
            </ElCol>
            <ElCol {...{ lg: 12, sm: 24 }} style="position: relative;">
              {state.detail?.id && (
                <MapLocation
                  ref={mapLocationRef}
                  detail={state.detail}
                  onSetHandleChange={onSetHandleChange}
                />
              )}
            </ElCol>
          </ElRow>
          {/* 导入 */}
          {state.importVisible && (
            <ImportExcelBatch
              batchNum={props.record.batchNum}
              onHandleImportFile={() => {
                proSaasTableRef.value?.toSearch()
              }}
              doCancel={() => {
                state.importVisible = false
              }}
            />
          )}
          {/* 导出 */}
          {state.exportVisible && (
            <ExportExcel
              visible={state.exportVisible}
              dispatchType="base/ExportBatchExport"
              columns={proSaasTableRef.value?.filterColumns}
              payload={{
                params: {
                  titleStats: state.titleStats,
                  buildAreas: state.buildAreas,
                  batchNum: props.record.batchNum,
                  exportName: state.exportName
                }
              }}
              exportNumber={proSaasTableRef.value?.pagination.total}
              onCancel={handleChangeExportModal}
            />
          )}
        </ElCard>
      )
    }
  }
})
